#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
script usage:
    python version.py -h
    python version.py -f <build.gradle> [-b <base>] [-p <prefix>]
"""

import re
import optparse
import os
import sys


VER_CODE = 'versionCode'
VER_NAME = 'versionName'
VER_CODE_PATT = VER_CODE + '.*?(\d+)'
VER_NAME_PATT = VER_NAME + '.*?[\'\"](.*)[\'\"]'


def find(s, pattern, update):
    m = re.search(pattern, s)
    if m:
        v = m.group(1)
        return m.start(1), m.end(1), v, update(v)


def version(settings, ver_code_update, ver_name_update):
    if not settings or not os.path.exists(settings):
        sys.exit('not found the version settings file: %s' % settings)

    settings_bak = settings + '.bak'
    if os.path.exists(settings_bak):
        print('the backup file already existed: %s' % settings_bak)
    else:
        os.rename(settings, settings_bak)

    with open(settings_bak, 'r') as i, open(settings, 'w') as o:
        code, name = False, False
        for s in i.xreadlines():
            if not code:
                ret = find(s, VER_CODE_PATT, ver_code_update)
                if ret:
                    start, end, code, code_new = ret
                    s = s[:start] + str(code_new) + s[end:]
            if not name:
                ret = find(s, VER_NAME_PATT, ver_name_update)
                if ret:
                    start, end, name, name_new = ret
                    s = s[:start] + name_new + s[end:]
            o.write(s)
        if code: print('%s: %s > %s' % (VER_CODE, code, code_new))
        if name: print('%s: %s > %s' % (VER_NAME, name, name_new))


def _parse_args():
    parser = optparse.OptionParser()
    parser.add_option('-f', '--file', dest='settings', metavar='build.gradle',
        help='the version settings file')
    parser.add_option('-b', '--base', dest='base', metavar='1000000',
        type='int', default=1000000, help='the version code base value')
    parser.add_option('-p', '--prefix', dest='prefix', metavar='dailybuild_',
        default='dailybuild_', help='the version name prefix value')
    options, args = parser.parse_args()
    return options


if __name__ == '__main__':
    options = _parse_args()
    version(options.settings,
        lambda v: int(v) + options.base,
        lambda v: options.prefix + v)
